MobX is a simple state management solution for JavaScript apps.
In this article, we’ll look at how to use MobX 6 to add state management into our JavaScript apps.
Disposing Autorun
When we don’t need to watch a store for changes anymore, we should dispose of any watchers we created.
To do this, we can call the function returned by autorun
, which returns a function that lets us remove it from memory when we’re done using it.
For instance, we can write:
import { makeObservable, observable, computed, action, autorun } from "mobx";
class Count {
count = 0;
get doubleCount() {
return this.count * 2;
}
constructor(count) {
makeObservable(this, {
count: observable,
doubleCount: computed,
increment: action
});
this.count = count;
}
increment() {
this.count++;
}
}
const store = new Count(1);
const dispose = autorun(() => {
console.log(store.count);
});
store.increment();
dispose();
We create a store with the count
observable, doubleCount
computed state, and the increment
action.
Then we instantiate it and assign the returned object to the store
.
Next, we call autorun
to watch the values we want.
We assign the returned function to the dispose
variable.
Then we call the store.increment
action to increment the count
state value which will trigger the autorun
callback to run.
Then we call dispose
to remove the watcher created by autorun
.
Watching Observables
In addition to using the autorun
function to watch MobX store states, we can use the reaction
function.
It takes a function that returns the value we want to watch as the first argument.
The first argument is another function that has the current and previous value being observed as the parameters.
And then we can do something with them in the callback.
For instance, we can write:
import {
makeObservable,
observable,
computed,
action,
autorun,
reaction
} from "mobx";
class Count {
count = 0;
get doubleCount() {
return this.count * 2;
}
constructor(count) {
makeObservable(this, {
count: observable,
doubleCount: computed,
increment: action
});
this.count = count;
}
increment() {
this.count++;
}
}
const store = new Count(1);
reaction(
() => store.count,
(currCount, prevCount) => {
console.log(currCount, prevCount);
}
);
store.increment();
We have the same store as before.
But we call the reaction
function with the 2 callbacks.
The 1srt callback returns the value of the store.count
state.
The 2nd callback has the current and previous values of store.count
respectively.
The 2nd callback will run when we call store.increment
.
This lets us have more fine-grained control of what we want to watch in the store.
Conclusion
We can watch values with more fine-grained control with the reaction
function provided by MobX.
Also, we should dispose of watchers created by the autorun
function when we no longer need them.